# Create your views here.
from django.http import HttpResponse
from django.views.decorators.cache import cache_page 

from simpleavatar.models import Photo

import os
from google.appengine.api import memcache
def get_default_photo():
    default_photo_key="p_default"
    image_data= memcache.get(default_photo_key)
    if image_data is not None:
        return image_data
    
    base="%s/%s"%(os.getcwd(),"../..")
    f=open("%s/%s"%(base,"static/photo.jpg"), "rb")
    image_data = f.read()
    f.close()
    memcache.add(default_photo_key, image_data, 60)
    return image_data


def photo(request, user_id=None):
    image_data=""
    if user_id is None:
        image_data=get_default_photo()
    else:
        user_id=user_id.decode('utf-8').encode('ascii')
        #gr_q=Greeting.all().filter('user_key = ', user_id)
        #gr=gr_q.get()
        image_key='p_%s'%user_id
        image_data=memcache.get(image_key)
        if image_data is not None:
            #return image_data
            #break
            return HttpResponse(image_data, mimetype="image/png")
        
        gr=Photo.get_by_key_name(image_key)
        
        if gr is None:
            image_data=get_default_photo()
        else:
            image_data=gr.avatar
            memcache.add(image_key,image_data,60)
    return HttpResponse(image_data, mimetype="image/png")